<template>
	<view class="pb-safe-area" @tap="hideMore">
		<swiper class="screen-swiper square-dot" indicator-color="rgba(255,255,255,.45)"
			indicator-active-color="var(--xl-primary)" :indicator-dots="true" :autoplay="true">
			<swiper-item v-for="(url, index) in find.thumbs" :key="index">
				<image :src="url" mode="aspectFit" class="swiper-image"></image>
			</swiper-item>
		</swiper>
		<view class="p-4 flex flex-column grid-gap-4">
			<view class="bg-white p-4 rounded-4 flex flex-column grid-gap-2">
				<view class="flex grid-gap-2">
					<text class="flex-1 h8 font-weight-600">{{ find.nickname }}</text>
					<x-tag type="primary" bg v-if="!find.reservation_disabled">最早可约：{{ find.appointment_time }}</x-tag>
					<x-tag type="dark" light text v-else>休息中</x-tag>
				</view>
				<view class="flex grid-gap-4">
					<text class="flex-1 h9 text-grey">已服务：{{ find.order_num }}单</text>
					<view class="flex flex-center grid-gap-2" @tap="collect()">
						<image src="@/static/icons/collect_active.png" v-if="find.is_collect" mode="scaleToFill"
							style="width: 16px;height: 16px;" />
						<image v-else src="@/static/icons/collect.png" mode="scaleToFill"
							style="width: 16px;height: 16px;" />
						<text class="font-weight-600"
							:class="[find.is_collect ? 'text-danger-light-3' : 'text-placeholder']">{{ find.collect_num
							}}</text>
					</view>
				</view>
				<text class="text-grey h9">从事健康行业{{ find.work_meet }}年，期待您的预约</text>
			</view>
			<view class="tab  flex flex-y-center">
				<view v-for="(item, index) in navList" :key="index" class="h9 font-weight-600 tab-item text-grey flex-1"
					@tap="changeNavTab(item.value)">
					<text :class="{ 'item-primary-active': navTbale === item.value }">{{
						WebConfigStore.replaceIndustryPersonnelName(item.label) }}</text>
				</view>
			</view>
			<view v-if="navTbale === 'service'" class="flex flex-column grid-gap-4">
				<template v-if="serviceList.length > 0">
					<view class="bg-white rounded-4 p-4" v-for="(item, index) in serviceList" :key="index">
						<x-project-item :project="item">
							<template #action>
								<x-input-number v-model="item.num"></x-input-number>
							</template>
						</x-project-item>
					</view>
				</template>
				<view class="vh-30 flex flex-center" v-else>
					<x-empty type="order" :text="WebConfigStore.replaceIndustryPersonnelName('该技师暂无服务')"></x-empty>
				</view>
			</view>

			<view v-else-if="navTbale === 'moments'">
				<view class="flex flex-column grid-gap-4 moments" v-if="moments.length > 0">
					<view class="p-4 moments-item border-top" v-for="(item, index) in moments" :key="index">
						<x-moments-item :item="item" :tap-num="tapNum">
							<template #more>
								<view class="flex-1 p-2 flex flex-center grid-gap-1" @tap="like(item, index)">
									<template v-if="item.is_like">
										<uni-icons type="hand-up-filled" color="var(--xl-primary)"></uni-icons>
										<text class="h10 text-primary text-nowrap">取消</text>
									</template>
									<template v-else>
										<uni-icons type="hand-up" color="var(--xl-primary)"></uni-icons>
										<text class="h10 text-primary text-nowrap">赞</text>
									</template>
								</view>
								<!-- <view class="flex-1 p-2 flex flex-center grid-gap-1">
									<uni-icons type="chat-filled" color="var(--xl-primary)"></uni-icons>
									<text class="h10 text-primary text-nowrap">评论</text>
								</view> -->
							</template>
						</x-moments-item>
					</view>
					<x-more :status="momentsLoading" @load="getList()"></x-more>
				</view>
				<view v-else class="vh-30 flex flex-center">
					<x-empty type="log" text="暂无动态"></x-empty>
				</view>
			</view>

			<view v-show="navTbale === 'comment'" class="flex flex-column grid-gap-4">
				<template v-if="find.comments && find.comments.length > 0">
					<view class="bg-white rounded-4 p-4" v-for="(item, index) in find.comments" :key="index">
						<x-comment-item :item="item" />
					</view>
				</template>
				<view class="vh-30 flex flex-center" v-else>
					<x-empty type="log" text="暂无评论"></x-empty>
				</view>
				<text class="bg-white rounded-4 p-4 text-center h10 text-grey"
					v-if="find.comments && find.comments_count > find.comments.length"
					@tap="$page.open('/pages/comment/index?action=technician&id=' + find.technician_id)">
					查看全部({{ find.comments_count }})条评论
				</text>
			</view>

			<view v-show="navTbale === 'qualification'" class="content rounded-4 flex flex-column">
				<image v-for="(item, index) in find.qualifications" :key="index" :src="item.url" lazy-load mode="scaleToFill"
					:style="item.style" @load="contentLoad($event, index)" />
			</view>
		</view>
		<view class="x-tabbar-placeholder pb-safe-area" v-if="serviceList.length > 0">
			<view class="x-tabbar pb-safe-area" style="z-index:100;">
				<view class="flex-1 flex flex-center px-4">
					<view class="flex-1">
						<text class="text-grey h9" v-if="proCount > 0">
							已选<text class="text-danger-light-3 h9 mx-2">{{ proCount }}</text>项服务项目
						</text>
						<text class="h10 text-placeholder" v-else>
							选择服务项目开始预约
						</text>
					</view>
					<button class="btn-dark-light-3 btn-round" size="mini" disabled
						v-if="find.reservation_disabled">休息中</button>
					<button class="btn-primary-light-1 btn-round mx-0" size="mini" @tap="goReserva()"
						:disabled="proCount < 1 || find.reservation_disabled" v-else>立即预约</button>
				</view>
			</view>
		</view>

		<!-- 立即预约 -->

		<x-loading v-if="loading" />
		<x-login ref="xLoginRef" @success="getDetails(find.technician_id)" />
	</view>
</template>

<script setup lang="ts">
import { ref, nextTick, computed,watchEffect } from 'vue';
import { $page, $api, $message, useStorage, login,$helper } from '@/utils';
import { onLoad, onReachBottom, onPageScroll, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app';
import { useWebConfigStore, useUserStore, useRefs } from "@/stores";
const WebConfigStore = useWebConfigStore();
const UserStore = useUserStore();
const { USERINFO } = useRefs(UserStore);
const { WEBCONFIG } = useRefs(WebConfigStore);
const xLoginRef = ref();
const loading = ref(false);
const find = ref({});
const navList = ref([
	{
		label: '服务项目',
		value: 'service'
	},
	{
		label: '技师动态',
		value: 'moments'
	},
	{
		label: '用户评价',
		value: 'comment'
	}
]);
watchEffect(() => {
	if(WEBCONFIG.value?.show_qualifications){
		if(!navList.value.find((item:any) => item.value === 'qualification')){
			navList.value.push({
				label: '资质证书',
				value: 'qualification'
			})
		}
	}else{
		navList.value = navList.value.filter((item:any) => item.value !== 'qualification');
	}
});
const navTbale = ref('service');
const serviceList = ref([]);
const proCount = computed(() => {
	return serviceList.value.filter((item: any) => item.num > 0).length;
});
const moments = ref([]);
const changeNavTab = (val: string) => {
	navTbale.value = val;
	if (val === 'service' && serviceList.value.length === 0) {
		nextTick(() => {
			getServiceList();
		});
	}
	if (val === 'moments' && moments.value.length === 0) {
		nextTick(() => {
			getMoments();
		});
	}
}
const getDetails = (id: any) => {
	if (loading.value) return;
	loading.value = true;
	$api.Technician.details(id).then((data: any) => {
		find.value = data;
		$page.title(data.nickname);
		changeNavTab(navTbale.value);
	}).catch((res: any) => {
		uni.showModal({
			title: '提示',
			content: res.msg,
			showCancel: false,
			success: () => {
				$page.back();
			}
		});
	}).finally(() => {
		loading.value = false;
	});
}
const getServiceList = () => {
	loading.value = true;
	$api.Service.list({
		technician_id: find.value.technician_id
	}).then((data: any) => {
		serviceList.value = data;
	}).finally(() => {
		loading.value = false;
	});
}
const collect = () => {
	if (!UserStore.hasLogin()) {
		return login({}, xLoginRef.value);
	}
	$api.Collect.technician(find.value.technician_id).then((data: any) => {
		find.value.is_collect = data.state;
		if (data.state) {
			find.value.collect_num++;
		} else {
			find.value.collect_num--;
		}
	}).catch((err: any) => {
		$message.error(err.msg);
	})
}
const goReserva = () => {
	let ReservaData = {
		technician: find.value,
		service: serviceList.value.filter(item => item.num > 0)
	};
	useStorage().set('ReservaData', ReservaData).then(() => {
		if (!UserStore.hasLogin()) {
			return login({
				redirect: 'pages/technician/details',
				params: {
					id: find.value.technician_id
				}
			}, xLoginRef.value);
		}
		if (WEBCONFIG.value?.force_realname && USERINFO.value?.is_realname !== 1) {
			uni.showModal({
				title: '提示',
				content: '请先完成实名认证',
				confirmText: '去认证',
				success: (res) => {
					if (res.confirm) {
						$page.open('/pages/user/account/realname')
					}
				}
			})
			return;
		}
		$page.open('/pages/order/confirm', true);
	}).catch(() => {
		$message.error('页面通信错误，请重试');
	})
}
const momentsSearch = ref({
	page: 1
})
const momentsLoading = ref('loadmore');
const tapNum = ref(0);
const getMoments = () => {
	if (momentsLoading.value === 'loading' || momentsLoading.value === 'nomore') return;
	momentsLoading.value = 'loading';
	momentsSearch.value.technician_id = find.value.technician_id;
	$api.Moments.list(momentsSearch.value).then((data: any) => {
		moments.value = [...moments.value, ...data.data];
		momentsSearch.value.page++;
		if (data.current_page >= data.last_page) {
			nextTick(() => {
				momentsLoading.value = 'nomore';
			})
		}
	}).catch(() => {
		nextTick(() => {
			momentsLoading.value = 'nomore';
		})
	}).finally(() => {
		if (momentsLoading.value === 'loading') {
			momentsLoading.value = 'loadmore';
		}
	})
}
const like = (item: any, index: number) => {
	if (!UserStore.hasLogin()) {
		return login({}, xLoginRef.value);
	}
	$api.Moments.like({ id: item.id }).then((res: any) => {
		item.is_like = res.data.state;
		if (res.data.state) {
			item.like_list.push({ uid: USERINFO.value.id, nickname: USERINFO.value.nickname });
		} else {
			item.like_list = item.like_list.filter((find: any) => find.uid !== USERINFO.value.id);
		}
	}).catch((err: any) => {
		$message.error(err.msg);
	})

}
const hideMore = () => {
	tapNum.value++;
	if (tapNum.value > 1000000) {
		tapNum.value = 0;
	}
}
const imageWidth = $helper.info().windowWidth - 32;
const contentLoad = (e: any, index: number) => {
	const scaling = e.detail.width / imageWidth;
	const h = e.detail.height / scaling;
	find.value.qualifications[index].style = {
		width: `${imageWidth}px`,
		height: `${h}px`
	};
}
onPageScroll(({ scrollTop }: { scrollTop: number }) => {
	hideMore();
})

onLoad((options: any) => {
	if (options.nav) {
		navTbale.value = options.nav;
	}
	// #ifdef MP-WEIXIN
	if (options.scene) {
		const scene = decodeURIComponent(options.scene).split('&');
		scene.forEach((item) => {
			const arr = item.split('=');
			options[arr[0]] = arr[1];
		})
	}
	// #endif
	getDetails(options.id);
})
onReachBottom(() => {
	if (navTbale.value === 'moments') {
		getMoments();
	}
})
onShareAppMessage(() => {
	return $page.shareMessage({
		title: find.value.nickname,
		path: `/pages/technician/details?id=${find.value.technician_id}`
	})
})
onShareTimeline(() => {
	return $page.shareTimeline({
		title: find.value.nickname,
		path: `/pages/technician/details?id=${find.value.technician_id}`
	})
})
</script>

<style lang="scss" scoped>
.screen-swiper {
	height: 750rpx;

	.swiper-image {
		width: 100%;
		height: 750rpx;
	}
}

.tab {
	height: 50px;
	position: sticky;
	top: 0;
	z-index: 999;
	background-color: #FAFAFA;

	&-item {
		height: 50px;
		line-height: 50px;
		display: inline-flex;
		justify-content: center;
		align-items: center;

		.item-primary-active {
			padding: 0;
		}
	}
}

.content {
	background-color: #FFFFFF;
	overflow: hidden;

	img {
		max-width: 100%;
	}
}

.moments {
	&-item:nth-child(1) {
		border-top: 0;
	}
}
</style>
